package com.shizhi.usp.usb;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.os.AsyncTaskCompat;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.shizhi.usp.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

/**
 * @author Created by Administrator on  2018-03-16
 * @version 1.0.
 */

public class UsbInfoFra extends Fragment {

    private ListView mListView;
    private UsbManager mUsbManager;
    private Activity mContext;
    private static UsbInfoFra mFra;

    private static final String ACTION_USB_PERMISSION = "com.shizhi.usb.Permission";

    public static UsbInfoFra getInstance() {
        if (mFra == null) mFra = new UsbInfoFra();
        return mFra;
    }


    private AdapterView.OnItemClickListener mOnItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String usbName = ((TextView) view).getText().toString();
            boolean foundDevice = false;
            for (UsbDevice device : mUsbManager.getDeviceList().values()) {
                if (device.getDeviceName().equals(usbName)) {
                    if (mUsbManager.hasPermission(device)) {
                        UsbDetailDialog.showDialog(mContext, usbName);
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setMessage("请授权，usb需要系统授权！！！")
                                .setPositiveButton("确定", (dialog, id1) -> {
                                    // FIRE ZE MISSILES!
                                    dialog.cancel();
                                    PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent(ACTION_USB_PERMISSION), 0);
                                    mUsbManager.requestPermission(device, pendingIntent);
                                })
                                .setNegativeButton("取消", (dialog, id1) -> {
                                    // User cancelled the dialog
                                    dialog.cancel();
                                });
                        // Create the AlertDialog object and return it
                        builder.create().show();
                    }
                    foundDevice = true;
                    break;
                }
            }
            if (!foundDevice)
                Toast.makeText(mContext, String.format("usb:%s", "null"), Toast.LENGTH_SHORT).show();

        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUsbManager = (UsbManager) getContext().getSystemService(Context.USB_SERVICE);
        mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(android.R.layout.list_content, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mListView = (ListView) view.findViewById(android.R.id.list);
        mListView.setOnItemClickListener(mOnItemClickListener);
        refresh();
    }

    @SuppressLint("StaticFieldLeak")
    private void refresh() {
        AsyncTaskCompat.executeParallel(new AsyncTask<Object, Object, List<String>>() {
            @Override
            protected List<String> doInBackground(Object... params) {
                HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
                Set<String> strings = deviceList.keySet();
                List<String> mData = new ArrayList<>(strings);
                Collections.sort(mData, (o1, o2) -> {
                    //按busNum正序排序
                    String substring = o1.substring(o1.lastIndexOf("/") + 1);
                    Integer busNum1 = Integer.valueOf(substring);
                    Integer busNum2 = Integer.valueOf(o2.substring(o2.lastIndexOf("/") + 1));
                    if (busNum1 < busNum2) return -1;
                    if (busNum1 > busNum2) return 1;
                    return 0;
                });
                return mData;
            }

            @Override
            protected void onPostExecute(List<String> strings) {
                super.onPostExecute(strings);
                if (mContext == null) return;
                String[] strings1 = strings.toArray(new String[]{});
                mListView.setAdapter(new ArrayAdapter<>(mContext, android.R.layout.simple_list_item_1, strings1));
                if (mListView.getHeaderViewsCount() == 0 && strings1.length > 0) {
                    Button refresh = new Button(mContext);
                    refresh.setText("刷新");
                    refresh.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            refresh();
                        }
                    });
                    ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    refresh.setLayoutParams(lp);
                    mListView.addHeaderView(refresh);
                }

            }
        });
    }


}
